//
//  PPEbookPreviewViewController.m
//  pickpic
//
//  Created by 胡文广 on 2017/4/16.
//  Copyright © 2017年 MicroDream. All rights reserved.
//

#import "PPEbookPreviewViewController.h"
#import "UIImageView+WebCache.h"
#import "PPProgressView.h"
#import "PPPhoto.h"
#import "PPPhotoView.h"
#import "PPTemplateInnerModel.h"
#import "PPPictureLoadingProgressView.h"
//#import "PPToolBarView.h"
//屏幕宽
#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define ScreenHeight [UIScreen mainScreen].bounds.size.height
#define JLKeyWindow [UIApplication sharedApplication].keyWindow

#define bigScrollVIewTag 101

#define kCodeImageWH 120
@interface PPEbookPreviewViewController ()<UIScrollViewDelegate>

/**
 *  底层滑动的scrollview
 */
@property (nonatomic,weak) UIScrollView *bigScrollView;
/**
 *  黑色背景view
 */
@property (nonatomic,strong) UIView *blackView;
/**
 *  原始frame数组
 */
@property (nonatomic,strong) NSMutableArray *originRects;

@property (nonatomic,strong) PPPhotoView *photoDescView;

@property (nonatomic,assign) BOOL isHidden;

@property (nonatomic,assign) CGFloat lastDescViewHeight;

@property (nonatomic,strong) NSMutableArray *photoScrollViews;

@property (nonatomic,assign) BOOL isEditAlbumImage;


@property (nonatomic,strong) UIButton *musicBtn;

@property (nonatomic,strong) UIButton *moreBtn;
@end

@implementation PPEbookPreviewViewController
- (NSMutableArray *)photoScrollViews{

    if (!_photoScrollViews) {
        _photoScrollViews = [NSMutableArray  array];
    }
    return _photoScrollViews;
}
- (PPPhotoView *)photoDescView{

    if (!_photoDescView) {
        _photoDescView = [[PPPhotoView alloc] init];
    }
    return _photoDescView;
}
-(NSMutableArray *)originRects{
    
    if (_originRects==nil) {
        
        _originRects = [NSMutableArray array];
        
    }
    
    return _originRects;
    
}

+ (instancetype)photoBrowser{
    
    return [[self alloc] init];
}

- (void)viewDidLoad{

    [super viewDidLoad];
    //0.创建黑色背景view
//    [self setupBlackView];
    [self.view addSubview:self.blackView];
    
    //1.创建bigScrollView
    [self setupBigScrollView];
    
    [self show];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(isScrollViewEnable:) name:PPNotice_isEditImage object:nil];
    

}
- (void)isScrollViewEnable:(NSNotification *)notice{

    self.isEditAlbumImage = [notice.object boolValue];
    
    self.bigScrollView.scrollEnabled = !(self.isEditAlbumImage);
    
    
}

#pragma mark 创建黑色背景
- (UIView *)blackView{

    if (!_blackView ) {
        _blackView = [[UIView alloc] init];
    }
    return _blackView;
}
#pragma mark 创建背景bigScrollView

-(void)setupBigScrollView{
    UIScrollView *bigScrollView = [[UIScrollView alloc] init];
    bigScrollView.backgroundColor = self.normalStyle?[UIColor blackColor]:[UIColor whiteColor];
    bigScrollView.delegate = self;
    bigScrollView.tag = bigScrollVIewTag;
    bigScrollView.pagingEnabled = YES;
    bigScrollView.bounces = YES;
    bigScrollView.showsHorizontalScrollIndicator = NO;
    CGFloat scrollViewX = 0;
    CGFloat scrollViewY = 0;
    CGFloat scrollViewW = ScreenWidth;
    CGFloat scrollViewH = self.view.frame.size.height;
    bigScrollView.frame = CGRectMake(scrollViewX, scrollViewY, scrollViewW, scrollViewH);
    [self.view addSubview:bigScrollView];
    
    self.bigScrollView = bigScrollView;
    
}

-(void)show{
    
    //2.获取原始frame
    [self setupOriginRects];
    
    //3.设置滚动距离
    self.bigScrollView.contentSize = CGSizeMake(ScreenWidth*self.photos.count, 0);
    self.bigScrollView.contentOffset = CGPointMake(ScreenWidth*self.currentIndex, 0);

    
    //4.创建子视图
    [self setupSmallScrollViews];

}

#pragma mark 创建子视图
-(void)setupSmallScrollViews{

    for (int i=0; i<self.photos.count; i++) {
        
        UIScrollView *smallScrollView = [self creatSmallScrollView:i];

        PPPhoto *photo = [self addTapWithTag:i];
        
        if (i == 0) {
            //添加音乐按钮
            
            
            
            //切换九宫格
        }

        photo.tag = i;
        photo.pics = self.pictures;
        smallScrollView.backgroundColor = WHITE;
        
        [smallScrollView addSubview:photo];
        
        
        //处理逻辑
        if (photo.style||photo.lastStyle) {
            //封面
            photo.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight-64);
            
        }else if (photo.desc.length > 0) {
            photo.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight-64);
            
        }else if(photo.innerModel){
            photo.totalPage = photo.innerModel.totalPage;
            photo.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight-64);
        }else{
            
            
            PPPictureLoadingProgressView *loopEbook = [self creatProgressViewLoopWithTag:i];
            PPProgressView *loop = [self creatLoopWithTag:i];
    
            if (self.normalStyle) {
                smallScrollView.backgroundColor = BLACK;
                 [smallScrollView addSubview:loop];
            }else{
                
                [smallScrollView addSubview:loopEbook];
            }
            
            
        
            NSURL *bigImgUrl = [NSURL URLWithString:photo.bigImgUrl];
            //检查图片是否已经缓存过
            [[SDImageCache sharedImageCache] queryDiskCacheForKey:photo.bigImgUrl done:^(UIImage *image, SDImageCacheType cacheType) {
                
                if (image==nil) {
                    loopEbook.hidden = NO;
                    loopEbook.progress = 0.001;
                    
                    loop.hidden = NO;
                }
                
            }];
            
            
            [photo sd_setImageWithURL:bigImgUrl placeholderImage:nil options:SDWebImageRetryFailed | SDWebImageLowPriority progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                
                //设置进度条
                loopEbook.progress = (CGFloat)receivedSize/(CGFloat)expectedSize;
                loop.progressValue = (CGFloat)receivedSize/(CGFloat)expectedSize;
                
            } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                
                if (image!=nil) {
                     loop.hidden = YES;
                    loopEbook.hidden = YES;
                    smallScrollView.backgroundColor = CLEAR;
                    
                    //下载回来的图片
                    if (cacheType==SDImageCacheTypeNone) {
                        [self setupPhotoFrame:photo];
                    }else{
                        photo.frame = [self.originRects[i] CGRectValue];
                        [UIView animateWithDuration:0.3 animations:^{
                            [self setupPhotoFrame:photo];
                        }];
                    }
                    
                }else{
//                    //图片下载失败
//                    photo.bounds = CGRectMake(0, 0, 240, 240);
//                    photo.center = CGPointMake(ScreenWidth/2, self.view.frame.size.height/2);
//                    photo.contentMode = UIViewContentModeScaleAspectFit;
//                    photo.image = [UIImage imageNamed:@"preview_image_failure"];
//                    [loop removeFromSuperview];
                }
                
            }];

        
        }
        
    }
    
}

- (void)setupPhotoFrame:(PPPhoto *)photo{
    
    UIScrollView *smallScrollView = (UIScrollView *)photo.superview;
    
//    self.blackView.alpha = 0.9;
    
    CGFloat ratio = (double)photo.image.size.height/(double)photo.image.size.width;
    
    CGFloat bigW = ScreenWidth;
    CGFloat bigH = ScreenWidth*ratio;
    
    if (bigH<self.view.frame.size.height) {
        photo.bounds = CGRectMake(0, 0, bigW, bigH);
        photo.center = CGPointMake(self.view.frame.size.width/2, (ScreenHeight-64)/2);
    }else{//设置长图的frame
        photo.frame = CGRectMake(0, 0, bigW, bigH);
        smallScrollView.contentSize = CGSizeMake(self.view.frame.size.width, bigH);
    }
    

}

- (UIScrollView *)creatSmallScrollView:(int)tag{
    
    UIScrollView *smallScrollView = [[UIScrollView alloc] init];
    
//    PPPhoto *photo = self.photos[tag];
//    smallScrollView.backgroundColor = [UIColor clearColor];
//
//    if (photo.innerModel) {
//        smallScrollView.backgroundColor = WHITE;
//        self.bigScrollView.backgroundColor = WHITE;
//    }
//    
    smallScrollView.tag = tag;
//    smallScrollView.frame = CGRectMake(ScreenWidth*tag, 0, ScreenWidth, self.view.frame.size.height);
    smallScrollView.frame = CGRectMake(ScreenWidth*tag, 0, ScreenWidth,self.bigScrollView.bounds.size.height);
    smallScrollView.delegate = self;
    if (!self.changeSize) {
        smallScrollView.maximumZoomScale=3.0;
        smallScrollView.minimumZoomScale=1;
    }
    
    
    [self.bigScrollView addSubview:smallScrollView];
    
    return smallScrollView;
    
}

- (PPPhoto *)addTapWithTag:(int)tag{
    
    PPPhoto *photo = self.photos[tag];
    
    photo.BlockStartEdit = ^{
        
        
    };
    photo.BlockAccomplishEdit = ^{
        
    
        
    };
    
    photo.tag = tag;
    UITapGestureRecognizer *photoTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(photoTap:)];
//    UITapGestureRecognizer *zonmTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zonmTap:)];
//    zonmTap.numberOfTapsRequired = 2;
//    [photo addGestureRecognizer:zonmTap];
    [photo addGestureRecognizer:photoTap];
    
    //zonmTap失败了再执行photoTap，否则zonmTap永远不会被执行
//    [photoTap requireGestureRecognizerToFail:zonmTap];
    
    return photo;
    
}

- (PPProgressView *)creatLoopWithTag:(int)tag{
    
    PPProgressView *loop = [[PPProgressView alloc] init];
    loop.tag = tag;
    loop.frame = CGRectMake(0,0 , 70, 70);
    
    loop.center = CGPointMake(ScreenWidth/2, self.view.frame.size.height/2 - 64);
    loop.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
    loop.hidden = YES;
//    UITapGestureRecognizer *loopTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(loopTap:)];
//    [loop addGestureRecognizer:loopTap];
    return loop;
    
}
- (PPPictureLoadingProgressView *)creatProgressViewLoopWithTag:(int)tag{

    PPPictureLoadingProgressView *loop = [[PPPictureLoadingProgressView alloc] init];
    loop.backgroundColor = CLEAR;
    loop.valueColor = [UIColor colorWithHexString:@"#A4A4B3"];
    loop.trackColor = [UIColor colorWithHexString:@"#F2F2F2"];
    loop.tag = tag;
    loop.bounds = CGRectMake(0,0 ,kProgressSize, kProgressSize);
    loop.center = CGPointMake(ScreenWidth/2, SCREEN_HEIGHT/2 - 64 - 64/2);
//    loop.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
    
    return loop;

}

//-(void)zonmTap:(UITapGestureRecognizer *)zonmTap{
//    
//    [UIView animateWithDuration:0.3 animations:^{
//        
//        UIScrollView *smallScrollView = (UIScrollView *)zonmTap.view.superview;
//        smallScrollView.zoomScale = 3.0;
//        
//    }];
//    
//}

-(void)photoTap:(UITapGestureRecognizer *)photoTap{
    
    PPPhoto *photo1 = self.photos[photoTap.view.tag];
    photo1.isFull = self.isHidden;
    [photo1 hiddenKeyboard];
    
    if (self.isPreviewFullScreen) { return; }
    self.isHidden = !self.isHidden;
    
    if (self.photoDescView) {
        [UIView animateWithDuration:0.5
                         animations:^{
                             self.photoDescView.alpha = self.isHidden?0.0:0.5;
                         }completion:^(BOOL finished){
                             [self.photoDescView setHidden:self.isHidden?YES:NO];
                         }];
    }
    PPPhoto *photo = self.photos[photoTap.view.tag];
    if (!self.isHidden && photo.photoDesc.length > 0) {
        [self.photoDescView removeFromSuperview];

        self.lastDescViewHeight = [self.photoDescView getSpaceLabelHeight:photo.photoDesc withFont:kNormalInnerDescFont withWidth:ScreenWidth-kLeftAndRightMargin*2]+kNormalInnerDescBottom + kNormalInnerDescTop;
        
        self.photoDescView .desc = photo.photoDesc;

        self.photoDescView.frame = CGRectMake(0,self.view.frame.size.height,SCREEN_WIDTH,self.lastDescViewHeight);
        [UIView animateWithDuration:.5 animations:^{
            self.photoDescView .frame = CGRectMake(0,self.view.frame.size.height-self.lastDescViewHeight, SCREEN_WIDTH,self.lastDescViewHeight);
        }];
        [self.view addSubview:self.photoDescView ];
    }


    if ([self.delegate respondsToSelector:@selector(ebookPreviewViewControllerTabView:)]) {
        [self.delegate ebookPreviewViewControllerTabView:(PPPhoto *)photoTap.view];
    }
    
    //    //1.将图片缩放回一倍，然后再缩放回原来的frame，否则由于屏幕太小动画直接从3倍缩回去，看不完整
    //    PPPhoto *photo = (PPPhoto *)photoTap.view;
    //    UIScrollView *smallScrollView = (UIScrollView *)photo.superview;
    //    smallScrollView.zoomScale = 1.0;
    //
    //    //1.1如果是长图片先将其移动到CGPointMake(0, 0)在缩放回去
    //    if (CGRectGetHeight(photo.frame)>ScreenHeight) {
    //        smallScrollView.contentOffset = CGPointMake(0, 0);
    //    }
    //
    //    //2.再取出原始frame，缩放回去
    //    CGRect frame = [self.originRects[photo.tag] CGRectValue];
    //
    //    [UIView animateWithDuration:0.3 animations:^{
    //
    //        photo.frame = frame;
    //        self.blackView.alpha = 0;
    //
    //    }completion:^(BOOL finished) {
    //
    //        [self removeFromSuperview];
    //
    //    }];
    
//    self.isHidden = !self.isHidden;
//    [[UIApplication sharedApplication] setStatusBarHidden:self.isHidden];
//    
//    [self.showViewController.navigationController setNavigationBarHidden:self.isHidden animated:TRUE];
    
}

//-(void)loopTap:(UITapGestureRecognizer *)tap{
//    
//    [UIView animateWithDuration:0.3 animations:^{
//        
//        self.blackView.alpha = 0;
//        tap.view.alpha = 0;
//        
//    }completion:^(BOOL finished) {
//        
//        [self removeFromSuperview];
//        
//    }];
//    
//}

#pragma mark 获取原始frame

-(void)setupOriginRects{
    
    for (PPPhoto *photo in self.photos) {
        
        UIImageView *sourceImageView = photo.sourceImageView;
        CGRect sourceF = [self.view convertRect:sourceImageView.frame fromView:sourceImageView.superview];
        [self.originRects addObject:[NSValue valueWithCGRect:sourceF]];
        
    }
    
}

#pragma mark UIScrollViewDelegate

//告诉scrollview要缩放的是哪个子控件
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    
    if (scrollView.tag==bigScrollVIewTag) return nil;
    
    PPPhoto *photo = self.photos[scrollView.tag];
    return photo;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView{
    
    if (scrollView.tag==bigScrollVIewTag) return;
    
    PPPhoto *photo = (PPPhoto *)self.photos[scrollView.tag];
    
    CGFloat photoY = (self.view.frame.size.height-photo.frame.size.height)/2;
    CGRect photoF = photo.frame;
    
    if (photoY>0) {
        photoF.origin.y = photoY;
        
    }else{
        photoF.origin.y = 0;
        
    }
    
    photo.frame = photoF;
    
    

    
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale{
    
    //如果结束缩放后scale为1时，跟原来的宽高会有些轻微的出入，导致无法滑动，需要将其调整为原来的宽度
    if (scale == 1.0) {
        CGSize tempSize = scrollView.contentSize;
        tempSize.width = ScreenWidth;
        scrollView.contentSize = tempSize;
        CGRect tempF = view.frame;
        tempF.size.width = ScreenWidth;
        view.frame = tempF;
        
    }
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    int currentIndex = scrollView.contentOffset.x/ScreenWidth;
    
    
    //图片描述处理
    if (self.currentIndex!=currentIndex && scrollView.tag==bigScrollVIewTag) {
        
        self.currentIndex = currentIndex;
        
        for (UIView *view in scrollView.subviews) {
            
            if ([view isKindOfClass:[UIScrollView class]]) {
                UIScrollView *scrollView = (UIScrollView *)view;
                scrollView.zoomScale = 1.0;
            }
            
        }
        
    }

    
    if (self.normalStyle) {
        
        [self showPhotoDescIndex:currentIndex];
    }
}
- (void)showPhotoDescIndex:(NSInteger)currentIndex{

    if (!self.normalStyle) {
        return;
    }
    
    PPPhoto *photo = self.photos[currentIndex];
    if (currentIndex != 0 && photo.photoDesc.length > 0 && !self.isHidden) {
        
        self.photoDescView.hidden = NO;

       self.lastDescViewHeight =  [self.photoDescView getSpaceLabelHeight:photo.photoDesc withFont:kNormalInnerDescFont withWidth:ScreenWidth-kLeftAndRightMargin*2] + kNormalInnerDescBottom + kNormalInnerDescTop;
        
        self.photoDescView .desc = photo.photoDesc;

        self.photoDescView.frame = CGRectMake(0,self.view.frame.size.height,SCREEN_WIDTH,self.lastDescViewHeight);
        [UIView animateWithDuration:.5 animations:^{
        self.photoDescView .frame = CGRectMake(0,self.view.frame.size.height-self.lastDescViewHeight, SCREEN_WIDTH,self.lastDescViewHeight);
        }];
        
        [self.view addSubview:self.photoDescView ];
    }

}
/**
 *  @param scrollView 将要开始的滚动视图
 */
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    
    self.photoDescView.hidden = YES;
    [self.photoDescView removeFromSuperview];
    

}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{

    NSInteger currentIndex = scrollView.contentOffset.x/ScreenWidth;

    if ([self.delegate respondsToSelector:@selector(ebookPreviewScrollViewDidScrollIndex:)]) {
        [self.delegate ebookPreviewScrollViewDidScrollIndex:currentIndex];
    }
  

}
- (void)viewDidLayoutSubviews{

    [super viewDidLayoutSubviews];
    
//    self.toolBar.frame = CGRectMake(0, self.view.height - 44, self.view.width, 44);
    
    self.blackView.frame = self.view.bounds;
    self.bigScrollView.frame = self.view.bounds;
    
    if (!self.isPreviewFullScreen) {
        [UIView animateWithDuration:.5 animations:^{
            
            self.photoDescView.frame = CGRectMake(0,self.view.frame.size.height - self.lastDescViewHeight, self.view.frame.size.width, self.lastDescViewHeight);
        }];
    }
    
}
#pragma mark 设置frame

-(void)setFrame:(CGRect)frame{
    
    frame = CGRectMake(0, 0, ScreenWidth, self.view.frame.size.height);
    
    [self setFrame:frame];
    
}


//#pragma mark --toolBar
//- (PPToolBarView *)toolBar{
//    
//    if (!_toolBar) {
//        _toolBar = [PPToolBarView toolBarView];
//        _toolBar.backgroundColor = COLORA(245, 245, 245);
//        _toolBar.delegate = self;
//    }
//    return _toolBar;
//}
//- (void)showToolBar{
//    
//    [self.view addSubview:self.toolBar];
//}
//- (void)hiddenToolBar{
//    
//    [self.toolBar removeFromSuperview];
//}
@end
